<?php
namespace addon\mall\controller;
use app\common\controller\AddonAdminBase;
use tpfcore\Core;
use \tpfcore\helpers\Json;
// +----------------------------------------------------------------------
// | Author: yaoyihong <510974211@qq.com>
// +----------------------------------------------------------------------
/**
 * ============================================================================
 * 版权所有 2017-2077 tpframe工作室，并保留所有权利。
 * @link http://www.tpframe.com/
 * @copyright Copyright (c) 2017 TPFrame Software LLC
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！未经本公司授权您只能在不用于商业目的的前提下对程序代码进行修改和使用；
 * 不允许对程序代码以任何形式任何目的的再发布
 * ============================================================================
 */
class Goods extends AddonAdminBase
{
    public function index(){
      	$this->addonTemplate('index',[
          "list"=>Core::loadAddonModel($this->name)->getGoods([
          		"order"=>"id desc",
          		'paginate'=>['rows' => 10],
          ])
      	]);
    }
    public function add(){
      IS_POST && $this->jump(Core::loadAddonModel($this->name)->saveGoods($this->param));
      $listShopConfig = Core::loadAddonModel("ShopConfig")->getShopConfig(['sign'=>"shop_config"]);
      $listShopConfig = empty($listShopConfig)?$listShopConfig:Json::jsonValueToArray($listShopConfig->toArray());
      $this->addonTemplate('add',[
        "listGoodsType" => Core::loadAddonModel("GoodsType")->getGoodsType([
          "where"=>["status"=>1]
        ]),
        "categorys"=>Core::loadAddonModel("GoodsCategory")->getTreeGoodsCategory(),
        "listGoodsBrand"=>Core::loadAddonModel("GoodsBrand")->getGoodsBrand(),
        "listShopConfig"=>$listShopConfig
      ]);
    }

    public function edit(){
      IS_POST && $this->jump(Core::loadAddonModel($this->name)->saveGoods($this->param));
      $listShopConfig = Core::loadAddonModel("ShopConfig")->getShopConfig(['sign'=>"shop_config"]);
      $listShopConfig = empty($listShopConfig)?$listShopConfig:Json::jsonValueToArray($listShopConfig->toArray());
      $list = Core::loadAddonModel($this->name)->getGoods([
        "where"=>['id'=>$this->param['id']]
      ]);
      if(empty($list)){
        $this->jump([RESULT_ERROR,"该产品不存在"]);
      }
      $this->addonTemplate('edit',[
        "list"=>$list[0],
        "listGoodsType" => Core::loadAddonModel("GoodsType")->getGoodsType([
          "where"=>["status"=>1]
        ]),
        "categorys"=>Core::loadAddonModel("GoodsCategory")->getTreeGoodsCategory(['parentid'=>$list[0]['category_id']]),
        "listGoodsBrand"=>Core::loadAddonModel("GoodsBrand")->getGoodsBrand(),
        "listPhoto"=>Core::loadAddonModel("GoodsPhoto")->getGoodsPhoto(['where'=>["goods_id"=>$this->param['id']],"order"=>"id asc"]),
        "listShopConfig"=>$listShopConfig
      ]);
    }

    public function del(){
    	 $this->jump(Core::loadAddonModel($this->name)->delGoods($this->param));
    }
    public function storage(){
      $data=$this->param;
      if(isset($data['act']) && $data['act']=="save_attr_group"){
        Core::loadAddonModel("GoodsStorage")->delGoodsStorageALL($data['attr_data']);
        $this->jump(Core::loadAddonModel("GoodsStorage")->saveGoodsStorageALL($data['attr_data']));
      }
      $listAttr = Core::loadAddonModel("GoodsAttr")->getGoodsAttr([
        "field"=>["__GOODS_ATTR__.*,__GOODS_ATTRIBUTE__.name"],
        "where"=>['goods_id'=>$data['id'],"__GOODS_ATTRIBUTE__.select_type"=>1],
        "join"=>["join"=>"__GOODS_ATTRIBUTE__","condition"=>"__GOODS_ATTRIBUTE__.id=__GOODS_ATTR__.attr_id","type"=>"left"],
      ]);

      foreach ($listAttr as $key => $value) {
        $listAttr[$key]=$value->toArray();
      }

      $type_id=[];
      foreach ($listAttr as $key => $value) {
        if(!in_array($value['attr_id'], $type_id)){
          $type_id[]=$value['attr_id'];
        }
      }

      $attr_list=[];
      foreach ($type_id as $key => $value) {
        foreach ($listAttr as $k => $v) {
          if($value==$v['attr_id']){
            $attr_list[$key]['id']=$value;
            $attr_list[$key]['name']=$v['name'];
            $attr_list[$key]['child'][]=$v;
          }
        }
      }
      /*
      $test = [
          "id"=>48,
          "name"=>"年代",
          "child"=>[
              ["id"=>100,"attr_id"=>48,"attr_price"=>"0.00","goods_id"=>1,"attr_value"=>1990,"name"=>"年代"],
              ["id"=>101,"attr_id"=>48,"attr_price"=>"0.00","goods_id"=>1,"attr_value"=>1998,"name"=>"年代"]
          ]
      ];
      $test2 = [
          "id"=>49,
          "name"=>"其它",
          "child"=>[
              ["id"=>103,"attr_id"=>49,"attr_price"=>"0.00","goods_id"=>1,"attr_value"=>"aaa","name"=>"其它"],
              ["id"=>104,"attr_id"=>49,"attr_price"=>"0.00","goods_id"=>1,"attr_value"=>"bbb","name"=>"其它"],
              ["id"=>105,"attr_id"=>49,"attr_price"=>"0.00","goods_id"=>1,"attr_value"=>"ccc","name"=>"其它"]
          ]
      ];
      $attr_list[]=$test;
      $attr_list[]=$test2;
      */
      // 默认数据
      $default_attr_list_data=[];
      $cache_arr=[];
      $arr=[];

      /*
      // 整体组合的方式
      foreach ($attr_list as $key => $value) {
        if($key==0){
          $arr = $cache_arr=$value['child']; continue;
        }
        foreach ($value['child'] as $k0 => $v0) {
          foreach ($cache_arr as $k1 => $v1) {
            $arr[$k1]['attr_value']=str_replace("\n", "", $v1['attr_value']).'-'.str_replace("\n","",$v0['attr_value']);
            $arr[$k1]['attr_id']=$v1['attr_id'].'-'.$v1['id'];
             $arr[$k1]['attr_id']=$v1['attr_id'].'-'.$v1['id'];
            $arr[$k1]['attr_price']=$v1['attr_price']+$v0['attr_price'];
            $arr[$k1]['goods_sn']="";
            $arr[$k1]['stock']="";
            $arr[$k1]['warn_stock']=1;
            $arr[$k1]['bar_code']="";
            $arr[$k1]['checked']=false;
          }
          foreach ($arr as $k2 => $v2) {
            $default_attr_list_data[]=$v2;
          }
        }

        $arr = $cache_arr=$default_attr_list_data;
        
        $default_attr_list_data=[];
      }
      */
      /*
      散列组合的方式
      */
      if(isset($data['act']) && $data['act']=="get_attr_group"){
      		$attr_ids = $data['attr_ids'];
	      	foreach ($attr_list as $key => $value) {
	        	foreach ($value['child'] as $k0 => $v0) {
	          		$default_attr_list_data[]=$v0;
	        	}
	      	}
	      	$group_ids=[];
	      	foreach ($default_attr_list_data as $key => $value) {
	      		foreach ($attr_ids as $k1 => $v1) {
	      			if($v1==$value['id']){
	      				$group_ids[$value['attr_id']][]=$v1;
	      			}
	      		}
	      	}
  			// 通过返回的有哪些ID组合
  			$arr = $this->get_attr_group(array_values($group_ids));
        //print_r($default_attr_list_data);die;
        $attr_list_str="";
  			foreach ($arr as $key => $value) { //有多少组合
  				$cache_arr=[];
  				foreach ($value as $k0 => $v0) {  // 每一个组合进行处理
  				  foreach ($default_attr_list_data as $k1 => $v1) {
  				    if($v1['id']==$v0){
  				      if(empty($cache_arr[0])){   // 第一次组合
  				        $cache_arr[0]=$v1;
                  $cache_arr[0]['goods_attr_ids']=$v1['id'];
                  $cache_arr[0]['goods_attr']=str_replace("\n", "", $v1['attr_value']);
                  $cache_arr[0]['goods_sn']="";
                  $cache_arr[0]['stock']=0;
                  $cache_arr[0]['warn_stock']=1;
                  $cache_arr[0]['bar_code']="";
                  $cache_arr[0]['price']=number_format($v1['attr_price'],2);
                  $cache_arr[0]['attr_list_str']=$v1['name'];
  				      }else{
                  $goods_attr_ids=explode(",",$cache_arr[0]['goods_attr_ids'].",".$v1['id']);
                  asort($goods_attr_ids);
  				        $cache_arr[0]['goods_attr_ids']=implode(",",$goods_attr_ids);
  				        $cache_arr[0]['goods_attr']=str_replace("\n", "", $cache_arr[0]['goods_attr']).','.str_replace("\n", "", $v1['attr_value']);
  				        $cache_arr[0]['goods_sn']="";
  				        $cache_arr[0]['stock']=0;
  				        $cache_arr[0]['warn_stock']=1;
  				        $cache_arr[0]['bar_code']="";
  				        $cache_arr[0]['price']=number_format($cache_arr[0]['attr_price']+$v1['attr_price'],2);
                  $cache_arr[0]['attr_list_str'].="、".$v1['name'];
  				      }
  				    }
  				  }
  				}
          unset($cache_arr[0]['id']);
  				$all[]=$cache_arr[0];
  			}
  			$this->jump([0,"success",$all]);
      }

      $listGoodsStorage = Core::loadAddonModel("GoodsStorage")->getGoodsStorage(["where"=>["goods_id"=>$data['id']]]);
      $attr_ids_arr = [];
      if($listGoodsStorage){
        foreach ($listGoodsStorage as $key => $value) {
          unset($listGoodsStorage[$key]['id']);
          $attr_ids_arr=array_merge($attr_ids_arr,explode(",", $value['goods_attr_ids']));
        }
        $attr_ids_arr=array_unique($attr_ids_arr);
      }

      $this->addonTemplate('storage',[
        "listGoodsStorage"=>json_encode($listGoodsStorage),
        "id"=>$data['id'],
        "attr_list"=>json_encode($attr_list),
        "list"=>[],
        "attr_ids_default"=>json_encode($attr_ids_arr)
      ]);
    }


  private function get_attr_group($arr){
        if(empty($arr)) return $arr;

        if(count($arr)==1) return array_chunk($arr[0], 1);

        $cache_arr = array_shift($arr); 

        if (!is_array($cache_arr)) {
            $cache_arr = array($cache_arr);
        }

        $cache_arr = array_chunk($cache_arr, 1);
      
        do {
            $new_arr = array();
            $next = array_shift($arr);

            if (!is_array($next)) {
                $next = array($next);
            }

            foreach ($cache_arr as $p) {
                foreach (array_chunk($next, 1) as $q) {
                    $new_arr[] = array_merge($p, $q);
                }
            }
            $cache_arr = $new_arr;
        } while ($arr);

        return $new_arr;
  }

}
